package com.aaa.dang.modules.review.service.impl;

import com.aaa.dang.common.entity.BedInfo;
import com.aaa.dang.common.systemlog.annotation.SysLog;
import com.aaa.dang.common.util.BaseContrllor;
import com.aaa.dang.common.util.ResultModel;
import com.aaa.dang.modules.review.dao.IReviewDao;
import com.aaa.dang.modules.review.service.IReviewService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.aaa.dang.common.systemconst.ISystemConst.*;

/**
 * @Author: ymk
 * @Date: 2018/12/15 20:59
 * @description:
 */
@Service
public class ReviewServiceImpl extends BaseContrllor implements IReviewService {
    @Autowired
    private IReviewDao dao;
    @Autowired
    private ResultModel model;

    /**
     * 查询所有申请入住的申请单
     * @param query
     * @return
     */

    @Override
    public ResultModel getliveAll(Map<String, Object> query) {
        int pageNo =Integer.parseInt(query.get("page")+"");
        int pageSize =Integer.parseInt(query.get("limit")+"");
        System.out.println(dao.getliveAll(query));
        PageHelper.startPage(pageNo,pageSize);
        try {
            model.setData(dao.getliveAll(query));
            model.setCount(dao.getliveTotal(query));
            model.setCode(SUCCESS_CODE);
            model.setMsg("查询成功");


        }catch (Exception e){
            model = returnErrorInfo("查询失败");
        }
        finally {
            return model;
        }
    }

    /**
     * 入住审核通过
     * @param query
     * @return
     */
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "入住审核通过")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public ResultModel passlive(Map<String,Object> query) {
        int room_type = Integer.parseInt(query.get("room_type") + "");
        int user_sex = Integer.parseInt(query.get("user_sex") + "");
        int room_id=Integer.parseInt(query.get("room_id")+"");
        Map<String,Object> map=new HashMap<>();
        map.put("end_time",query.get("end_time"));
        map.put("user_id",query.get("user_id"));
        map.put("id",query.get("id"));
        map.put("bed_id",query.get("bed_id"));
        map.put("pay_type",query.get("pay_type"));
        try{
            //查询床位表是否已存在其他用户
            int i = dao.userisExit(map);
            if(i==0){
               model=returnSuccessInfo("该床铺已有人，请驳回");
            }else{
                //查询当前用户是否已有床铺
                int count = dao.userbedisExit(map);
                if(count==1){
                    model=returnErrorInfo("当前用户已有床位,请驳回");
                }else{
                    //当前用户与房间类型不同
                    if(room_type!=2 && room_type!=user_sex){
                    model=returnErrorInfo("与用户性别不同，请驳回");
                    //空房更新房间类型
                }else if(room_type==2) {
                    dao.updateroomtype(room_id, user_sex);
                }else if(room_type==user_sex){
                    int b = dao.pass(map);
                    //在用户床位表添加用户id
                    dao.addUser(map);
                    //查询当前房间人数
                    int peoplenum = dao.getpeoplenum(query);
                    //更新房间人数
                    dao.updateRoomNum(room_id, peoplenum);
                    //更新入住到期时间
                    dao.addlivetimefree(map);
                    //获取退宿时间
                    int retireTime = dao.getRetireTime(map);
                    if(retireTime>0){
                        //更新退宿时间
                        dao.updateRetireTime(map);
                        model=returnSuccessInfo("老用户且入住成功");
                    }else{
                        model=returnSuccessInfo("入住成功");
                    }



                    }


                }

            }

        }catch (Exception e){
            model=returnErrorInfo("入住失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        }

        return model;
    }

    /**
     *
     * 驳回入住审核
     * @param query
     * @return
     */
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "驳回入住审核")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public ResultModel rejectlive(Map<String,Object> query) {
        try{
            int b=dao.reject(query);
            model=returnSuccessInfo("更新成功");

        }catch (Exception e){
            model=returnErrorInfo("更新失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return model;
    }

    /**
     * 查询所有离宿的申请单
     * @param query
     * @return
     */
    @Override
    public ResultModel getretireAll(Map<String, Object> query) {
        int pageNo =Integer.parseInt(query.get("page")+"");
        int pageSize =Integer.parseInt(query.get("limit")+"");
        PageHelper.startPage(pageNo,pageSize);
        try {
            model.setData(dao.getretireAll(query));
            model.setCount(dao.getretireTotal(query));
            model.setCode(SUCCESS_CODE);
            model.setMsg("查询成功");

        }catch (Exception e){
            model=returnErrorInfo("查询失败");
        }
        finally {
            return model;
        }
    }

    /**
     * 退宿申请审核通过
     * @param query
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "通过退宿申请审核")
    public ResultModel passretire(Map<String, Object> query) {
        int room_id=Integer.parseInt(query.get("room_id")+"");
        int pay_type=Integer.parseInt(query.get("pay_type")+"");
        SimpleDateFormat format=new SimpleDateFormat("yyyy-M-ddHH:mm:ss");
        try {
            int i = dao.isretire(query);
            if(i==FAULT_CODE){
                model=returnErrorInfo("该用户已退宿");
            }else{
                //获取退宿申请时间
                Date retire_time=format.parse(query.get("apply_time").toString());
                //获取用户到期时间
                Date end_time=dao.getEndtime(query);
                if(retire_time.getTime()>end_time.getTime()){
                    model=returnErrorInfo("租金不足需补钱，请驳回");
                }else{
                    //修改审核状态
                    int b=dao.passretire(query);
                    //删除床位
                    dao.deluserbed(query);
                    //获取房间人数
                    int peoplenum = dao.getpeoplenum(query);
                    //更新房间人数
                    dao.updateRoomNum(room_id,peoplenum);
                    //更新退宿时间
                    dao.addretiretime(query);
                    //更新已住时间
                    dao.updatestaytime(query);
                    //免租
                    if(pay_type==1){
                        model=returnSuccessInfo("免租人员提前离宿");
                    }else{
                        //查询最后交租数
                        Map<String,Object> rentmap = dao.getReturnRent(query);
                        Double rent=Double.parseDouble(rentmap.get("payment").toString());
                        //天数
                        int monthnum=Integer.parseInt(rentmap.get("month_num").toString());
                        //余天数
                        int days = dao.getdaysnum(query);
                        //应退钱
                        Double returnrent=(rent/monthnum)*days;

                        model=returnSuccessInfo("需要给该同学退"+returnrent+"元");
                    }

            }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return model;
    }

    /**
     * 驳回退宿审核
     * @param query
     * @return
     */
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "驳回入住审核")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public ResultModel rejectretire(Map<String,Object> query) {

        try{
            int b=dao.rejectretire(query);
           model=returnSuccessInfo("更新成功");

        }catch (Exception e){
            model=returnErrorInfo("更新失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return model;
    }

    /**
     * 查询所有租金审核
     * @param query
     * @return
     */

    @Override
    public ResultModel getrentAll(Map<String, Object> query) {
        int pageNo =Integer.parseInt(query.get("page")+"");
        int pageSize =Integer.parseInt(query.get("limit")+"");
        PageHelper.startPage(pageNo,pageSize);
        try {
            model.setData(dao.getrentAll(query));
            model.setCount(dao.getrentTotal(query));
            model.setCode(SUCCESS_CODE);
            model.setMsg("查询成功");

        }catch (Exception e){
            model=returnErrorInfo("查询失败");
        }
        finally {
            return model;
        }
    }

    /**
     * 租金审核通过
     * @param query
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "通过退宿审核")
    @Override
    public ResultModel passrent(Map<String, Object> query) {
        int id=Integer.parseInt(query.get("id")+"");
        try{
            //租金表
            dao.addpayrent(query);
            //更新到期时间
            dao.updateEndtime(query);
            //更新状态
            dao.updateRentState(id);
            model=returnSuccessInfo("更新成功");

        }catch (Exception e){
            model=returnErrorInfo("更新失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return model;
    }

    /**
     * 租金驳回
     * @param query
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "驳回退宿审核")
    @Override
    public ResultModel rejectrent(Map<String,Object> query) {
        try{
            int b=dao.rejectRent(query);
            model=returnSuccessInfo("更新成功");

        }catch (Exception e){
            model=returnErrorInfo("更新失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return model;
    }

    /**
     * 四级联动获取空床信息
     * @return
     */

    @Override
    public List<BedInfo> getbedInfo(int user_sex) {
        //获取小区
        List<BedInfo> area=dao.getArea();
        List<BedInfo> areachildren=new ArrayList<>();
        List<BedInfo> buildchildren=new ArrayList<>();
        List<BedInfo> roomchildren=new ArrayList<>();
        for(int i=0;i<area.size();i++){
            //获取楼栋
            areachildren=dao.getBuild(area.get(i).getValue());
            area.get(i).setChildren(areachildren);
            for (int j=0;j<areachildren.size();j++){
                //获取房间
                buildchildren=dao.getRoom(areachildren.get(j).getValue(),user_sex);
                areachildren.get(j).setChildren(buildchildren);
                for( int z=0;z<buildchildren.size();z++){
                    //获取床位
                    roomchildren=dao.getBed(buildchildren.get(z).getValue());
                    buildchildren.get(z).setChildren(roomchildren);
                }
            }

        }

        return area;
    }


    /**
     * 查询所有押金审核
     * @param query
     * @return
     */

    @Override
    public ResultModel getpositAll(Map<String, Object> query) {
        int pageNo =Integer.parseInt(query.get("page")+"");
        int pageSize =Integer.parseInt(query.get("limit")+"");
        System.out.println(dao.getpositAll(query));
        PageHelper.startPage(pageNo,pageSize);
        try {
            model.setData(dao.getpositAll(query));
            model.setCount(dao.getpositTotal(query));
            model.setCode(SUCCESS_CODE);
            model.setMsg("查询成功");

        }catch (Exception e){
            model=returnErrorInfo("查询失败");
        }
        finally {
            return model;
        }
    }

    /**
     * 押金通过
     * @param query
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "通过押金审核")
    @Override
    public ResultModel passposit(Map<String, Object> query) {
        Map<String,Object> map=new HashMap<>();
        map.put("user_id",query.get("user_id"));
        map.put("money",query.get("money"));
        int id=Integer.parseInt(query.get("id")+"");

        try{
            //更新押金
            dao.updateUserDeposit(map);
            //更新状态
            dao.updateDepositState(id);
            model=returnSuccessInfo("更新成功");

        }catch(Exception e){
            model=returnErrorInfo("更新失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return model;
    }

    /**
     * 押金驳回
     * @param query
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @SysLog(operateType = SysLog.Type.UPDATE,desc = "驳回押金审核")
    @Override
    public ResultModel rejectposit(Map<String,Object> query) {
        try{
            int b=dao.rejectposit(query);
            model=returnSuccessInfo("更新成功");

        }catch (Exception e){
            model=returnErrorInfo("更新失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return model;
    }

    /***
     * 获取未审核数量
     * @return
     */
    @Override
    public Map<String,Integer> getliveApplyUnaudited(){
        Map<String,Integer> map=new HashMap<>();
        try {
            //获取入住待审核数量
            int getliveApplyUnaudited = dao.getliveApplyUnaudited();
            //获取退宿待审核数量
            int getretireApplyUnaudited = dao.getretireApplyUnaudited();
            //获取租金待审核数量
            int getrentApplyUnaudited = dao.getrentApplyUnaudited();
            //获取押金待审核数量
            int getdepositApplyUnaudited = dao.getdepositApplyUnaudited();
            //获取维修待处理数量
            int repairUnaudited=dao.getrepairUnaudited();
            //待审核总数
            int applyCount=getdepositApplyUnaudited+getliveApplyUnaudited+getrentApplyUnaudited+getretireApplyUnaudited;

            map.put("applyCount",applyCount);
            map.put("repairCount",repairUnaudited);


        }catch (Exception e){

        }
        return map;

    }


}
